from datetime import datetime
import json

from django.core.paginator import Paginator
from django.http import JsonResponse

from lapi_app.models.management_model.point_config import Point_pid
from lapi_app.models.management_model.point_name import Point_name


def get_track_list(request):
    global track_data
    try:
        data = json.loads(request.body)
        # 判断事件名和事件来源
        if data["field_name"] == "" and data["pid"] is None:
            track_data = Point_name.objects.all().order_by("-id")
        elif data["field_name"] != "" and data["pid"] is not None:
            track_data = Point_name.objects.filter(field_name__contains=data["field_name"], p_id=data["pid"])
        elif data["field_name"] != "" and data["pid"] is None:
            track_data = Point_name.objects.filter(field_name__contains=data["field_name"])
        elif data["field_name"] == "" and data["pid"] is not None:
            track_data = Point_name.objects.filter(p_id=data["pid"])
        size_page = data["size_page"]
        current_pages = data["current_page"]
        track_total = len(track_data)
        result = []
        pid_list = []
        for track in track_data:
            track_dict = {
                "id": track.id,
                "pid": track.p_id,
                "pid_name": track.p.from_name,
                "field_name": track.field_name,
                "create_time": datetime.strftime(track.create_time, "%Y-%m-%d %H:%M:%S"),
                "update_time": datetime.strftime(track.update_time, "%Y-%m-%d %H:%M:%S"),
                "username": track.user.username,
            }
            pid_dict = {
                "pid": track.p_id,
                "pid_name": track.p.from_name
            }
            pid_list.append(pid_dict)
            result.append(track_dict)
        p = Paginator(result, size_page)
        page1 = p.page(current_pages)
        current_page = page1.object_list
        return JsonResponse({
            "code": 200,
            "message": "获取打点事件列表成功",
            "content": current_page,
            "track_total": track_total,
            "size_page": size_page,
            "current_page": current_pages,
            "pid_data": pid_list
        })
    except Exception as e:
        return JsonResponse({
            "code": 100,
            "message": str(e)
        })


def get_single_track(request):
    try:
        data = json.loads(request.body)
        id = data["id"]
        s_data = Point_pid.objects.filter(p_id=id)
        p_data = Point_pid.objects.get(id=id)
        result = []
        res_dict = {"attribute_config": {}, "action": p_data.field_name}
        for s in s_data:
            res_dict["attribute_config"].update({s.field_name: s.field_value})
        result.append(res_dict)
        return JsonResponse({
            "code": 200,
            "message": "获取打点事件列表成功",
            "content": result,
        })
    except Exception as e:
        return JsonResponse({
            "code": 100,
            "message": str(e)
        })


def start_track(request):
    try:
        data = json.loads(request.body)
        Point_name.objects.filter(username=data["username"]).delete()
        return JsonResponse({
            "code": 200,
            "message": "开始打点测试"
        })
    except Exception as e:
        return JsonResponse({
            "code": 100,
            "message": str(e)
        })


def get_track(request):
    data = json.loads(request.body)
    username = request.GET.get("username")
    for i in data:
        name = i["custom_field"]["action"]
        Point_name.objects.create(field_name=name, fiel_value=i, username=username)
    return JsonResponse({
        "code": 200
    })


def get_track_data(request):
    try:
        data = json.loads(request.body)
        username = data["username"]
        result = []
        for j in Point_name.objects.filter(username=username):
            p_dict = {
                "id": j.id,
                "content": j.field_name,
                "value": j.fiel_value,
                "timestamp": datetime.strftime(j.create_time, "%Y-%m-%d %H:%M:%S")
            }
            result.append(p_dict)
        return JsonResponse({
            "code": 200,
            "content": result
        })
    except Exception as e:
        return JsonResponse({
            "code": 100,
            "message": str(e)
        })
